package hospital

import (
	"encoding/json"
	"fmt"
	"gitee.com/cheneylau/components/web-server/model"
	"github.com/astaxie/beego/httplib"
	"sort"
	"time"
)

var url = "https://api.cmsfg.com/api/appointment/Scheduling?AppId=600100"

func Hospital(keShiCode string) ([]model.OkDoctor, string, error) {
	doctors, err := getDocters(keShiCode)
	if err != nil {
		return nil, "", err
	}

	var okDoctors []model.OkDoctor
	for _, doctor := range doctors.Result {
		sk, _ := getDocterStatus(doctor.DoctorWorkNum, keShiCode)
		for _, appointmentScheduling := range sk.Result.AppointmentScheduling {
			for _, schedulings := range appointmentScheduling.Schedulings {
				if schedulings.CanAppointment > 0 {
					date, _ := time.ParseInLocation("2006-01-02", schedulings.Date, time.Local)
					okDoctors = append(okDoctors, model.OkDoctor{
						Date:     schedulings.Date,
						DateTime: date,
						Doctor:   doctor,
					})
				}
			}
		}
	}

	result := fmt.Sprintln("可预约专家如下:")
	sort.Slice(okDoctors, func(i, j int) bool {
		return okDoctors[i].DateTime.Unix() < okDoctors[j].DateTime.Unix()
	})
	for _, value := range okDoctors {
		result += fmt.Sprintln("\t", value.Doctor.DoctorName, value.Date)
	}

	//fmt.Println(result)
	return okDoctors, result, nil
}

func getDocters(keShiCode string) (*model.ResultListDoctor, error) {
	startDate := time.Now().Format("2006-01-02")
	endDate := time.Now().Add(time.Hour * 24 * 30).Format("2006-01-02")
	params := fmt.Sprintf(`{"method":"GetHisSchedulingDoctorListNew","params":[{"AppId":"600100","RegisterType":"off","AppointmentType":"F,G,B,E,J,K,H,I,A,7,8,9","ParentCode":"%s","Date":"%s","EndDate":"%s","IsScheduleFilter":true}]}`, keShiCode, startDate, endDate)
	//获取医生
	req := GetRequest(url, params)
	s, err := req.String()
	if err != nil {
		return nil, err
	}

	var resDoctors model.ResultListDoctor
	err = json.Unmarshal([]byte(s), &resDoctors)
	if err != nil {
		return nil, err
	}

	return &resDoctors, nil
}

func getDocterStatus(doctorWorkNum string, keShiCode string) (*model.ResultDoctorScheduling, error) {
	startDate := time.Now().Format("2006-01-02")
	endDate := time.Now().Add(time.Hour * 24 * 30).Format("2006-01-02")
	params := fmt.Sprintf(`{"method":"GetScheduling","params":[{"AppId":"600100","DoctorWorkNum":"%s","DeptCode":"%s","RegisterType":"off","Date":"%s","EndDate":"%s","AppointmentType":"9"}]}`, doctorWorkNum, keShiCode, startDate, endDate)
	//获取医生
	req := GetRequest(url, params)
	s, err := req.String()
	if err != nil {
		return nil, err
	}

	var rds model.ResultDoctorScheduling
	err = json.Unmarshal([]byte(s), &rds)
	if err != nil {
		return nil, err
	}

	return &rds, nil
}

func GetKeShi() (*model.ResultListKeShi, error) {
	params := fmt.Sprintf(`{"method":"GetHisDeptList","params":[{"AppId":"600100"}]}`)
	//获取医生
	req := GetRequest(url, params)
	s, err := req.String()
	if err != nil {
		return nil, err
	}

	var rds model.ResultListKeShi
	err = json.Unmarshal([]byte(s), &rds)
	if err != nil {
		return nil, err
	}

	return &rds, nil
}

func GetRequest(url string, body string) *httplib.BeegoHTTPRequest {
	req := httplib.Post(url)
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36")
	req.Header("Host", "api.cmsfg.com")
	req.Header("sec-ch-ua", `"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"`)
	req.Header("Referer", "https://api.cmsfg.com/app/hospital/600100/index.html?code=021D0n000YjcyL1kUH20085Ayt0D0n0j&state=600100")
	req.Body(body)
	return req
}
